import { observable, action } from 'mobx';
import page from '../../apis/page';
import settings from '../../apis/settings';
import { isNormal, isLayout } from '../../components/designer/form/component/typeof';

export default class EdcFormReplyStore {
	@observable coms = [];
	@observable appid = '';
	@observable hasInit = '';
  	@observable replyInfo = {};

	@action init(appid) {
		this.appid = appid;

		Promise.all([
			page.getDesign(appid),
			settings.getReceipt(appid)
		]).then(([{ main, sub }, info]) => {
      		const coms = [];
			this.hasInit = false;
	
			main.forEach(com => {
				if (isLayout(com)) {
					com.config.coms.forEach(comId => {
					 if (comId) {
					   coms.push(sub[comId]);
					 }
					});
				} else if (isNormal(com)) {
					coms.push(com);
				}
			});
			
			this.replyInfo = info;
			this.hasInit = true;
			this.coms = coms;
		})
  	}
  
	@action onChange = (key, value) => {
		const info = this.replyInfo;

		Object.assign(info, { [key]: value });

		this.replyInfo = info;
	}
	
	@action onSave = () => {
		const params = Object.assign(this.replyInfo, { appid : this.appid });

		return settings.saveReceipt(params);
	}
}